#include "common.h"

void enable_gpio_clock(GPIO_TypeDef *GPIOx)
{
    if(GPIOx == GPIOA)
    {
        SYSCTRL_PeriphClkEnable(SYSCTRL_PERICLK_PA);
    }
    else if(GPIOx == GPIOB)
    {
        SYSCTRL_PeriphClkEnable(SYSCTRL_PERICLK_PB);
    }
    else if(GPIOx == GPIOC)
    {
        SYSCTRL_PeriphClkEnable(SYSCTRL_PERICLK_PC);
    }
    else if(GPIOx == GPIOD)
    {
        SYSCTRL_PeriphClkEnable(SYSCTRL_PERICLK_PD);
    }
}
void enable_gpio_nvic(GPIO_TypeDef *GPIOx)
{
    if(GPIOx == GPIOA)
    {
        EnableNvic(PORTA_IRQn, IrqLevel0, TRUE);
    }
    else if(GPIOx == GPIOB)
    {
        EnableNvic(PORTB_IRQn, IrqLevel0, TRUE);
    }
    else if(GPIOx == GPIOC)
    {
        EnableNvic(PORTC_IRQn, IrqLevel0, TRUE);
    }
    else if(GPIOx == GPIOD)
    {
        EnableNvic(PORTA_IRQn, IrqLevel0, TRUE);
    }
}
static void gpio_init(GPIO_TypeDef *GPIOx, uint32_t u32Pin, uint32_t u32Mode, uint32_t u32Pull)
{
    stc_gpio_init_t stcGpioInit = {0};
    enable_gpio_clock(GPIOx);
    REG_CLEARBITS(GPIOx->PU, u32Pin);
    REG_WRITE(GPIOx->BRR, u32Pin);
    stcGpioInit.u32Mode = u32Mode;
    stcGpioInit.u32Pin  = u32Pin;
    stcGpioInit.u32Pull = u32Pull;
    GPIO_Init(GPIOx, &stcGpioInit);
}
void gpio_set_out(GPIO_TypeDef *GPIOx, uint32_t u32Pin)
{
    gpio_init(GPIOx, u32Pin, GPIO_MODE_OUTPUT_PP, GPIO_PULL_NONE);
}
void gpio_set_in(GPIO_TypeDef *GPIOx, uint32_t u32Pin)
{
    gpio_init(GPIOx, u32Pin, GPIO_MODE_INPUT, GPIO_PULL_NONE);
}
void gpio_set_in_with_interrupt(GPIO_TypeDef *GPIOx, uint32_t u32Pin, uint32_t u32ExtI)
{
    stc_gpio_init_t stcGpioInit = {0};
    enable_gpio_clock(GPIOx);
    stcGpioInit.u32Mode = GPIO_MODE_INPUT | GPIO_MODE_EXTI;
    stcGpioInit.u32Pin  = u32Pin;
    stcGpioInit.u32Pull = GPIO_PULL_DOWN;
    stcGpioInit.u32ExtI = u32ExtI;
    GPIO_Init(GPIOx, &stcGpioInit);
    
    enable_gpio_nvic(GPIOx);
    
}
void system_delay1ms(uint32_t u32Cnt)
{   
	uint32_t ValNow,CNT = 0;
	uint32_t end = (u32Cnt*(SystemCoreClock/1000));
			   	 
	uint32_t StaVal = SysTick->VAL;        				    
	while(1)
	{
		ValNow=SysTick->VAL;	
		
		if(ValNow != StaVal)
		{			
			if(ValNow<StaVal)
            {
                CNT += StaVal -ValNow;
            }
			else
            {
                CNT += SysTick->LOAD - ValNow+StaVal;
            }				
			StaVal = ValNow;			
			if(CNT >= end ) 
            {
                break;
            }
		}
	}
}
void system_delay100us(uint32_t u32Cnt)
{
    uint32_t ValNow,CNT = 0;
	uint32_t end = (u32Cnt*(SystemCoreClock/10000));
			   	 
	uint32_t StaVal = SysTick->VAL;        				    
	while(1)
	{
		ValNow=SysTick->VAL;	
		
		if(ValNow != StaVal)
		{			
			if(ValNow<StaVal)
            {
                CNT += StaVal -ValNow;
            }
			else
            {
                CNT += SysTick->LOAD - ValNow+StaVal;
            }
            
			StaVal = ValNow;
            
			if(CNT >=end)
            {
                break;
            }
		}
	}
}